package cn.com.dhc.danlu.activity.message;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.danlu.dlsms.model.pub.res.MsgCountResponse;
import com.danlu.dlsms.model.pub.res.MsgNewestOneMessageResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.model.bus.MsgEvent;
import cn.com.dhc.danlu.model.bus.MsgEvent.MsgType;
import cn.com.dhc.danlu.util.ActivityUtils;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.TipCountUtil;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.BadgeView;
import cn.com.dhc.danlu.widget.loadlayer.LoaddingLayout;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.pushmsg.GetUnreadCountRequest;
import cn.com.hd.mall.web.webservices.entity.request.pushmsg.NewestOneMsg;
import cn.com.hd.mall.web.webservices.entity.request.pushmsg.SetMsgStatus;

import static cn.com.dhc.danlu.constant.MsgTypeConst.MsgTypeGroup;
import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @author wuhaiyang 消息tab 界面,当前界面可能涉及到及时刷新
 */
public class MessageContainerActivity extends BaseActivity {
    /***
     * holder容器
     */
    private LinearLayout llHolderContainer;

    /**
     * layer 切换布局
     */
    private LoaddingLayout llLayer;

    /***
     * 订单消息item项 其他消息item项
     */
    private LinearLayout llOrderMsg;
    private LinearLayout llOtherMsg;

    /***
     * 订单消息、其他消息 角标
     */
    private BadgeView mOrderMsgBadgeView;
    private BadgeView mOtherMsgBadgeView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //        getDelegate().setContentView(R.layout.layout_messagecontainer, R.layout_messagecontainer.class);
        setContentView(R.layout.activity_message_container);

        llLayer = (LoaddingLayout) findViewById(R.id.ll_layer);
        llHolderContainer = (LinearLayout) findViewById(R.id.ll_holder_container);

        EventBus.getDefault().register(this);

        llLayer.setRetryClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                llLayer.showLoaddingView();
                loadMessage();
            }
        });
    }

    /**
     * 界面可见的时候请求服务器刷新数据
     */
    @Override
    protected void onStart() {
        super.onStart();
        loadMessage();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 请求服务器获取订单消息和其他消息 最新一条消息和未读数量
     */
    private void loadMessage() {
        getNewestMsg();
    }

    /**
     * 获取所有消息类型的最新一条消息
     */
    private void getNewestMsg() {
        NewestOneMsg request = new NewestOneMsg();
        request.receiverUserId = agent.getLoginUser().getUserId();
        request.receiverCompanyId = agent.getLoginUser().getCompanyId();
        request.channelId = CommonConst.CHANNEL_ID;
        request.type = MsgTypeGroup.PURCHASE_ORDER_MSG + "," + MsgTypeGroup.MY_MSG + "," + MsgTypeGroup.DANLU_ENVELOP_MSG;
        agent.getMsgApi()
                .getNewestOneMsg(request)
                .compose(OperatorUtils.<MsgNewestOneMessageResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<MsgNewestOneMessageResponse>() {
                    @Override
                    protected void onSuccess(MsgNewestOneMessageResponse model) {
                        String orderMsg1 = model.getMessage().get(MsgTypeGroup.PURCHASE_ORDER_MSG); // 订单消息
                        String otherMsg = model.getMessage().get(MsgTypeGroup.MY_MSG); // 其他消息
                        String envelopMsg = "";
                        if (model.getMessage().get(MsgTypeGroup.DANLU_ENVELOP_MSG) != null) {
                            envelopMsg = model.getMessage().get(MsgTypeGroup.DANLU_ENVELOP_MSG);
                        }
                        if (!TextUtils.isEmpty(envelopMsg)) {
                            otherMsg = envelopMsg;
                        }
                        if (TextUtils.isEmpty(otherMsg)) {
                            otherMsg = getResources().getString(R.string.no_other_msg);
                        }
                        initHolderView();
                        bindData(orderMsg1, otherMsg);
                        if (!TextUtils.isEmpty(orderMsg1) || !TextUtils.isEmpty(otherMsg)) {
                            llLayer.showContentView();
                            getUnreadMsgCountRequest();
                        } else {
                            llLayer.showEmptyView();
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        llLayer.showErrorView(displayMessage);
                    }
                });
    }

    /**
     * 获取未读消息数目
     */
    private void getUnreadMsgCountRequest() {
        GetUnreadCountRequest request = new GetUnreadCountRequest();
        if (null == agent.getLoginUser()) {
            ActivityUtils.startLoginActivity(this);
            finish();
            return;
        }
        request.receiverUserId = agent.getLoginUser().getUserId();
        request.receiverCompanyId = agent.getLoginUser().getCompanyId();
        request.channelId = CommonConst.CHANNEL_ID;
        agent.getMsgApi()
                .getUnreadMsgCount(request)
                .compose(OperatorUtils.<MsgCountResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<MsgCountResponse>() {
                    @Override
                    protected void onSuccess(MsgCountResponse model) {
                        Map<String, Integer> unreadMap = model.getMsgCount().getUnreadCount();
                        int unreadOrderMsg = unreadMap.get(MsgTypeGroup.PURCHASE_ORDER_MSG);
                        int unreadOtherMsg = unreadMap.get(MsgTypeGroup.MY_MSG);
                        int unreadEnvelopMsg = 0;
                        if (null != unreadMap.get(MsgTypeGroup.DANLU_ENVELOP_MSG)) {
                            unreadEnvelopMsg = unreadMap.get(MsgTypeGroup.DANLU_ENVELOP_MSG);
                        }
                        unreadOtherMsg += unreadEnvelopMsg;
                        showCount(unreadOrderMsg, mOrderMsgBadgeView);
                        showCount(unreadOtherMsg, mOtherMsgBadgeView);
                    }
                });
    }

    /**
     * 初始化contentView相关控件和事件绑定
     */
    protected void initHolderView() {
        if (null == llOrderMsg) {
            llOrderMsg = (LinearLayout) View.inflate(this, R.layout.order_message_holder, llHolderContainer);
            mOrderMsgBadgeView = initBadgeView(llOrderMsg.findViewById(R.id.iv_msg_icon));
            llHolderContainer.getChildAt(0).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("llq", "onClick: fjaojfaojfoajfoajfoajf");
                    clickLogic(mOrderMsgBadgeView, MsgType.ORDER_MSG);
                }
            });
        }
        if (null == llOtherMsg) {
            llOtherMsg = (LinearLayout) View.inflate(this, R.layout.other_message_holder, llHolderContainer);
            mOtherMsgBadgeView = initBadgeView(llOtherMsg.findViewById(R.id.iv_msg_icon1));
            // hard Code --> because here is click conflict
            // bindaction
            llHolderContainer.getChildAt(1).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickLogic(mOtherMsgBadgeView, MsgType.OHTER_MSG);
                }
            });
        }
    }

    /**
     * badgeView 初始化设置
     */
    private BadgeView initBadgeView(View targetView) {
        BadgeView badgeView = new BadgeView(this, targetView);
        badgeView.setTextSize(10);
        badgeView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
        badgeView.setBadgeMargin(0);
        return badgeView;
    }

    /**
     * 界面跳转逻辑 角标变化通知 请求服务器 消息设置为已读状态
     *
     * @param type 跳转界面逻辑
     */
    private void clickLogic(BadgeView badgeView, MsgType type) {
        int needReduceCount = 0;
        if (null != badgeView.getTag()) {
            needReduceCount = (Integer) badgeView.getTag();
        }
        if (0 <= needReduceCount) {
            // 请求服务器 重置该类型消息的状态为已读 并且给MainMenuAct发送一条消息 去重新请求未读数量刷新角标
            setMsgHasRead(type);
        } else {
            // 跳转界面
            skipIntent(type);
        }
    }

    /**
     * 将指定消息类型 中所有消息置为已读
     */
    private void setMsgHasRead(final MsgType type) {
        SetMsgStatus request = new SetMsgStatus();
        request.receiverCompanyId = agent.getLoginUser().getCompanyId();
        request.receiverUserId = agent.getLoginUser().getUserId();
        request.type = type == MsgType.ORDER_MSG ? MsgTypeGroup.PURCHASE_ORDER_MSG : MsgTypeGroup.MY_MSG + "," + MsgTypeGroup.DANLU_ENVELOP_MSG;
        agent.getMsgApi().setMsgStatus(request)
                .compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        // 重置状态成功 刷新角标 界面跳转
                        if (type == MsgType.ORDER_MSG) {
                            if (null != mOrderMsgBadgeView.getTag()) {
                                showCount(0, mOrderMsgBadgeView);
                            }
                        } else if (type == MsgType.OHTER_MSG) {
                            if (null != mOtherMsgBadgeView.getTag()) {
                                showCount(0, mOtherMsgBadgeView);
                            }
                        }
                        skipIntent(type);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    protected void skipIntent(MsgType type) {
        Intent intent = new Intent(this, MessageListActivity.class);
        intent.putExtra(MessageListActivity._TYPE_ADAPTER, type);
        startActivity(intent);
    }

    /**
     * 针对指定的badgeView来刷新角标数量
     */
    private void showCount(int count, BadgeView badgeView) {
        badgeView.setTag(count);
        if (count > 0) {
            badgeView.show();
            badgeView.setText(TipCountUtil.cover(count, TipCountUtil.SMALL_FLAG));
        } else {
            badgeView.hide();
        }
    }

    /**
     * 数据绑定
     */
    public void bindData(String orderMsg, String otherMsg) {
        if (!TextUtils.isEmpty(orderMsg)) {
            TextView tvOrderMsg = (TextView) llOrderMsg.findViewById(R.id.tv_msg_content);
            tvOrderMsg.setText(orderMsg);
        }
        if (!TextUtils.isEmpty(otherMsg)) {
            TextView tvOtherMsg = (TextView) llOtherMsg.findViewById(R.id.tv_other_msg);
            tvOtherMsg.setText(otherMsg);
        }
    }

    /**
     * eventBus消息透传
     */
    @Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
    public void onUserEvent(MsgEvent event) {
        MsgType type = event.getType();
        String from = event.getEventFrom();
        if (from.equals(CommonConst.PushMsgFrom._FROM_PUSH_RECEIVER)) {
            // 消息来自推送接受 --> 说明有最新的消息 两种方式刷新 1、重新请求服务器 2、在原有的基础之上++
            getNewestMsg();
        }
    }
}